package com.umakr.ax.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author umakr
 */
public class AudioUtil{
    protected static final Log logger = LogFactory.getLog(AudioUtil.class);
    public static Integer getAudioDuration(String audioPath){
        File file = new File(audioPath);
        Integer audioTimeLength = 0;
        if(!file.exists()) {
            logger.info("文件不存在："+audioPath);
            return audioTimeLength;
        }else {
            String fileName = file.getName();
            String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
            String[]  suffixValue = {"mp3","amr","wav"};

            if (suffixValue[0].equals(suffix)) {
                return getMp3Duration(file);
            }else if(suffixValue[1].equals(suffix)){
                return getAmrDuration(file);
            }else if(suffixValue[2].equals(suffix)){
                return getWavDuration(file);
            }else {
                logger.info("===================暂不支持获取当前语音格式的音频长度======================");
                return audioTimeLength;
            }
        }
    }

    public static Integer getMp3Duration(File file) {
        Integer audioTimeLength = 0;
        try {
            MP3File f = (MP3File) AudioFileIO.read(file);
            MP3AudioHeader audioHeader = (MP3AudioHeader) f.getAudioHeader();
            audioTimeLength = audioHeader.getTrackLength();
        } catch (Exception e) {
            logger.error(e);
        }
        return  audioTimeLength;
    }

    public static Integer getAmrDuration(File file){
        long duration = -1;
        int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0,
                0, 0 };
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");

            // 文件的长度
            long length = file.length();
            // 设置初始位置
            int pos = 6;
            // 初始帧数
            int frameCount = 0;
            int packedPos = -1;

            // 初始数据值
            byte[] datas = new byte[1];
            while (pos <= length) {
                randomAccessFile.seek(pos);
                if (randomAccessFile.read(datas, 0, 1) != 1) {
                    duration = length > 0 ? ((length - 6) / 650) : 0;
                    break;
                }
                packedPos = (datas[0] >> 3) & 0x0F;
                pos += packedSize[packedPos] + 1;
                frameCount++;
            }
            // 帧数*20
            duration += frameCount * 20;
        }catch (Exception e) {
            logger.error(e);
        } finally {
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
        return (int) ((duration/1000)+1);
    }

    public static Integer getWavDuration(File file) {
        Clip clip = null;
        try {
            clip = AudioSystem.getClip();
            AudioInputStream ais = AudioSystem.getAudioInputStream(file);
            clip.open(ais);
        } catch (Exception e) {
            logger.error(e);
        }
        return (int) ((clip.getMicrosecondLength()/1000000D)+1);
    }
}
